import importlib
import pkgutil
from fastapi import FastAPI, APIRouter
from typing import List
import logging
import re

logger = logging.getLogger(__name__)

IS_PRE = False


def get_version_prefix(module_path: str) -> str:
    """从模块路径中提取前缀
    - 如果是 controller 直接子文件，返回空字符串
    - 如果是子目录中的文件，返回子目录名作为前缀
    """
    # 检查是否是 controller 的直接子文件
    if module_path.count('.') == 1 and module_path.startswith('controller.'):
        return ""

    # 否则提取子目录名作为前缀
    match = re.search(r'controller\.([^.]+)', module_path)
    if match:
        return f"/{match.group(1)}"
    return ""


def get_routes_from_module(module_path: str) -> List[APIRouter]:
    """从指定模块中获取所有路由"""
    routers = []
    try:
        module = importlib.import_module(module_path)
        if hasattr(module, 'router'):
            router = getattr(module, 'router')
            if isinstance(router, APIRouter):
                routers.append((router, module_path))
    except Exception as e:
        logger.error(f"Error loading module {module_path}: {str(e)}")
    return routers


def scan_routes(base_package: str) -> List[tuple[APIRouter, str]]:
    """递归扫描目录下的所有路由"""
    routers = []
    try:
        package = importlib.import_module(base_package)
        package_path = package.__path__

        for finder, name, is_pkg in pkgutil.walk_packages(package_path):
            full_name = f"{base_package}.{name}"

            if is_pkg:
                # 如果是包，递归扫描
                sub_routers = scan_routes(full_name)
                routers.extend(sub_routers)
            else:
                # 如果是模块，获取路由
                module_routers = get_routes_from_module(full_name)
                routers.extend(module_routers)
                if module_routers:
                    logger.info(f"Found routes in module: {full_name}")

    except Exception as e:
        logger.error(f"Error scanning package {base_package}: {str(e)}")

    return routers


def register_routes(app: FastAPI, api_prefix: str = "") -> None:
    """注册API目录下的所有路由"""
    base_package = "controller"

    logger.info(f"Starting to scan routes from package: {base_package}")

    # 扫描所有路由
    all_routers = scan_routes(base_package)

    # 注册找到的路由
    for router, module_path in all_routers:
        # 获取版本前缀
        if IS_PRE:
            version_prefix = get_version_prefix(module_path)
        else:
            version_prefix = ''
        # 组合完整的前缀
        full_prefix = f"{api_prefix}{version_prefix}"

        app.include_router(router, prefix=full_prefix)
        # 打印路由信息
        for route in router.routes:
            logger.info(f"Registered route: {full_prefix}{route.path} [{', '.join(route.methods)}]")

    logger.info(f"Total registered routers: {len(all_routers)}")